import React, {useState, Fragment, useEffect} from 'react';
import { useMetaInit } from './utils';
import { useEventsRegister, useInitData } from './use-events';
import { getLocal }  from '../_common/util';
import TableRender from '@/biz-components/table-render';
import { plus } from '../_common/numberPrecision';


interface hocEvents {
    tableButtonsEvents?: any,
    buttonsEvents?:any
}
// 计算汇总值
const FooterCalculate:React.FC<any> = (props: {
    calculateCol: Array<any>,
    dataSource:any,
    columns: any,
    expression?:any
  })=>{
    const [calTota, setCalTota] = useState<any>();
    const dataSource = props.dataSource;
    const columns = props.columns;
    // 获取列名
    const filterCol = ()=>{
       const colDisplay =  columns?.filter((i:any)=>(props?.calculateCol?.indexOf(i.key)>-1))?.map((a:any)=>{
         return {
          name: a.key,
          val: [],
          displayName: getLocal()==='zh_CN' ? `${a.label}汇总` : `${a.label}total`
         }
       })
       return colDisplay;
    }
    // 通过列名获取值并汇总
    useEffect(()=>{
        calTotal();
    },[dataSource])
    const calTotal  = ()=>{
      let col:any = filterCol() || [];
      for(let i=0; i<col?.length; i++){
        col[i].val = dataSource?.map((a:any)=>(a[col[i].name]))  as any;
      }
      for(let i=0; i<col?.length; i++){
        const val1 = col[i].val.shift() || '0';
        const val2 = col[i].val.shift() || '0';
        col[i].total = plus(val1, val2, ...(col[i].val || []));
      }
      setCalTota(col);
    }
    // 设置表达式动态计算值
    const expressionfunc = ()=>{
      const displayName =  getLocal()==='zh_CN' ? `汇总` : `total`;
      let total =  0;
      // 校验当前表达式是否包含$self
      if(props.expression?.indexOf('$self')<0){
           console.error('当前表达式不符合规则"`${$self.xx-$self.aa}`"');
      }else {
        var $self = {};
        for(let i=0; i<calTota.length; i++){
          $self[calTota[i].name] = calTota[i].total;
        };
        if(props.expression){
          total = eval(props.expression);
        }
        return <><span>{displayName}:</span><span>{total}</span></>
      }
    }
    console.log('calTota', calTota);
    return <Fragment>
      {
        props.expression ? expressionfunc(): null
      }
      {
        calTota?.map((i:any)=>{
          return <><span>{i.displayName}:</span><span>{i.total}</span></>
        })
      }
    </Fragment>

  }
export interface INestesTable{
    pageCode: string; // 获取列表的pagecode
    subCode?: string; // 子表格内容
    dataSource?: Array<any>; // 主表格dataSource
    editable?: true|false; // 是否可编辑
    calculateCol?: Array<any>;
    expression?:any;
    expandedRow?:boolean;
    map?: {
        text: string, // 作映射把子模型的字段映射到
        value: string, //
    }
    events?: hocEvents;
    api?:{
        type?: 'GET'| 'POST',
        url?: string,
        params?: Object
    }; // 获取远程数据
    onChange?: (...agn: any)=> void; // 将数据回传出去
    [propsName: string]: any;
}
const NestesTable: React.FC<INestesTable> = (props:any) => {
    const { pageCode, events, expandedRow=true, cb, loading, validator, subCode, editable, pagination=false, dataSource, nestDataSource, api, map, ...extraProps } = props;
    const [tabconfigs, setTabConfigs] = useMetaInit(pageCode);
    const [configs, setConfigs] = subCode ? useMetaInit(subCode) : [{tableButtons: [], buttons:[], tableColumns:[]}];
    const { tableButtons, buttons, tableColumns } = configs;
    const hookMapIns = React.useRef({
        tableButtonsEvents: {
        },
        buttonsEvents: {
        }
    })
    const columns = tabconfigs.tableColumns;
    const { getTableTopButton, operations } = useEventsRegister(hookMapIns, events, {
        history,
        pageCode,
        callback: cb,
        tableButtons,
        buttons,
        loading,
        validator,
    });
    const [tableData, setDataSource] = useInitData(dataSource, api, map);
    const expandedRowRender = (record: any) => {
        return <><TableRender
        operation={editable ? operations : ""}
        operAuths={tableButtons?.map(() => '')}
        extraAction={getTableTopButton()}
        metas={tableColumns || []}
        dataSource={record[map?.text] || []}
        pagination={false} />
        {props?.calculateCol ? <FooterCalculate
        calculateCol={props?.calculateCol}
        dataSource={record[map?.text] || []}
        columns={tableColumns || []}
        ></FooterCalculate> : null}
        </>
    }
    return <>
    <TableRender
    metas={columns || []}
    pagination={pagination}
    dataSource={tableData?.dataSource || []}
    isRequesting={loading}
    expandable={expandedRow ? { expandedRowRender } : {}}
    {...extraProps}
    >
    {
       expandedRow ? null: <FooterCalculate
       calculateCol={props?.calculateCol}
       dataSource={tableData?.dataSource || []}
       columns={tableColumns || []}
       ></FooterCalculate>
    }

    </TableRender>
    </>
}
export default NestesTable;


